var url = require("url");
var fs = require('fs');
var view_handler = require('./view_handler');
var router = {};

fs.readFile('routes', 'utf-8', function(err, data) {
  if(err) {
    console.error("ERROR: Could not open file: %s", err);
    process.exit(1);
  }

  var content = data.split('\n');
  var i = 0;
  for (i = 0; i < content.length; i++) {
    var values = content[i].split('=>');
    if (values[0] != '') {
      router[values[0].replace(' ', '')] = values[1].replace(' ', '');
    }
  }
});

function route(request, response, parameters) {
  var pathname = url.parse(request.url).pathname;
  console.log('Rounting request to ' + pathname);
  
  if (pathname == '/') {
    pathname = 'home';
  }
  
  try {
    var controller = router[pathname.replace('/', '')];
    if (controller != undefined) {
      var handler = require('./controller' + controller);
      handler.load(request, response, parameters);
    } else {
      view_handler.render_view(request, response, 'view/404.html');
    }
  } catch (err) {
    console.error(err.stack);
    response.end();
  }
}

exports.route = route;
